package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.MemberClient;
import com.robot.admin.client.OrdersClient;
import com.robot.admin.pojo.client.Member;
import com.robot.admin.service.AdminService;
import com.robot.admin.util.SendMessageUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台会员模块
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private MemberClient memberClient;
    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private CheckUtil checkUtil;
    @Autowired
    private SendMessageUtil sendMessageUtil;

    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @PostMapping(value = "findSearch/{page}/{size}")
    public Result findMemberBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindSearch(searchMap, page, size)));
    }

    /**
     * 会员列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{page}/{size}")
    public Result findMembers(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindMembers(page, size)));
    }

    /**
     * 会员详情
     *
     * @param id
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{id}/{page}/{size}")
    public Result findMemberById(@PathVariable String id, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        //会员信息
        Member memberInDb = JSON.parseObject(memberClient.thirdFindMemberById(id), Member.class);
        logger.info("memberInDb=" + memberInDb);
        String message = checkPojo(memberInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        //推荐人
        Member recommender = null;
        if (memberInDb.getRecommendId() != null) {
            recommender = JSON.parseObject(memberClient.thirdFindMemberById(memberInDb.getRecommendId()), Member.class);
        }
        logger.info("recommender=" + recommender);
        //累计支付成功的订单数
        String ordersCount = JSON.parseObject(ordersClient.thirdFindSubOrderCountByMemberId(memberInDb.getId()), String.class);
        //累计节省金额
        String ordersDiscountAmount = JSON.parseObject(ordersClient.thirdFindSubOrderDiscountAmountByMemberId(memberInDb.getId()), String.class);
        //累计消费金额
        String ordersPayAmount = JSON.parseObject(ordersClient.thirdFindSubOrderPayAmountByMemberId(memberInDb.getId()), String.class);

        HashMap<String, Object> map = new HashMap<>(3);
        map.put("member", memberInDb);
        map.put("recommender", recommender);
        map.put("ordersCount", ordersCount);
        map.put("ordersDiscountAmount", ordersDiscountAmount);
        map.put("ordersPayAmount", ordersPayAmount);
        map.put("orders", JSON.parseObject(ordersClient.thirdFindSubOrdersByMemberId(memberInDb.getId(), page, size)));
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 导出下级/我的团队队员列表并分页/邀请人ID是我的全部会员
     *
     * @param id
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "subordinate/{id}/{page}/{size}")
    public Result findMembersByRecommendId(@PathVariable String id, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindMembersByRecommendId(id, page, size)));
    }

    /**
     * 会员编辑
     *
     * @param id
     * @param member
     * @return
     */
    @PutMapping("{id}")
    @Transactional(rollbackFor = Exception.class)
    public Result updateMember(@PathVariable String id, @RequestBody Member member) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Member memberInDb = JSON.parseObject(memberClient.thirdFindMemberById(id), Member.class);
        logger.info("memberInDb=" + memberInDb);
        String message = checkPojo(memberInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        String phone = member.getPhone();
        if (phone != null && !"".equals(phone)) {
            if (!checkUtil.checkPhone(phone)) {
                return new Result(StatusCode.ERROR_INVALID_PHONE);
            }
        }

        String password = member.getPassword();
        if (password != null && !"".equals(password)) {
            member.setPassword(encoder.encode(member.getPassword()));
        }
        member.setId(id);
        UpdateUtil.copyNonNullProperties(member, memberInDb);
        memberClient.thirdUpdateMemberByMember(memberInDb);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 通过推荐人名字查询推荐列表
     *
     * @param searchMap 推荐人名称
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findMembersByRecommendName/{page}/{size}", method = RequestMethod.POST)
    public Result findMembersByRecommendName(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        String recommendName = (String) searchMap.get("recommendName");
        if (recommendName == null || "".equals(recommendName)) {
            return new Result(StatusCode.ERROR, "推荐人姓名必填");
        }

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindMembersByRecommendName(recommendName, page, size)));
    }

    /**
     * 通过推荐人手机号查询推荐列表
     *
     * @param searchMap 推荐人手机号
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findMembersByRecommendPhone/{page}/{size}", method = RequestMethod.POST)
    public Result findMembersByRecommendPhone(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        String recommendPhone = (String) searchMap.get("recommendPhone");
        if (recommendPhone == null || "".equals(recommendPhone)) {
            return new Result(StatusCode.ERROR, "推荐人手机号必填");
        }

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(memberClient.thirdFindMembersByRecommendPhone(recommendPhone, page, size)));
    }

    /**
     * 会员名下订单数
     *
     * @param memberId 会员id
     * @param page     页码
     * @param size     页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findOrdersByMemberId/{memberId}/{page}/{size}", method = RequestMethod.GET)
    public Result findOrdersByMemberId(@PathVariable String memberId, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(ordersClient.thirdFindSubOrdersByMemberId(memberId, page, size)));
    }

    /**
     * 消息推送
     *
     * @param map
     * @return
     */
    @PostMapping("messagePush")
    public Result sendSms(@RequestBody Map map) {
        Map<String, Object> resultMap = sendMessageUtil.sendMessage(map);
        return new Result(StatusCode.SUCCESS_SEND);
    }

    /**
     * 检查实体类是否存在
     *
     * @param memberInDb
     * @return
     */
    public String checkPojo(Member memberInDb) {
        if (memberInDb == null) {
            return ("该会员不存在");
        }
        if (memberInDb.getDeletedAt() != null) {
            return ("该会员已被删除");
        }
        return "";
    }
}
